package com.example.plugin.setting;

import com.example.plugin.config.DefaultTemplate;
import com.example.plugin.ui.TemplatePanel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 配置类
 *
 * @author lipan
 * @date 2022/1/16 9:47
 * @email 13160080997@163.com
 **/
public class GenerateSetting implements Configurable {

    private Map<String, DefaultTemplate> group;

    private TemplatePanel templatePanel;

    public static Settings settings = Settings.getInstance();

    @Nls(capitalization = Nls.Capitalization.Title)
    @Override
    public String getDisplayName() {
        return "Generate";
    }


    @Nullable
    @Override
    public JComponent createComponent() {
        JPanel panel = new JPanel(new BorderLayout());
        this.group = new LinkedHashMap<>();
        this.group.putAll(settings.getTemplateGroup());
        List<DefaultTemplate> list = new ArrayList<>();
        for(String name:this.group.keySet()){
            list.add(this.group.get(name));
        }
        templatePanel = new TemplatePanel(list);
        panel.add(templatePanel,BorderLayout.CENTER);
        return panel;
    }

    @Override
    public boolean isModified() {
        DefaultTemplate selectedItem = templatePanel.getSelectedItem();
        if(selectedItem==null){
            return false;
        }
        Editor editor = templatePanel.getEditor();
        Document document = editor.getDocument();

        if(!selectedItem.getText().equals(document.getText())){
            return true;
        }
        return false;
    }

    @Override
    public void apply() throws ConfigurationException {
        DefaultTemplate selectedItem = templatePanel.getSelectedItem();
        Editor editor = templatePanel.getEditor();
        Document document = editor.getDocument();
        selectedItem.setText(document.getText());
        group.put(selectedItem.getName(),selectedItem);
        settings.put(selectedItem);
    }
}
